package com.atguigu.cloud.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        // 创建基础线程池
        ExecutorService executor = new ThreadPoolExecutor(5, 200,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024), new CustomThreadFactory("custom-pool-"), new ThreadPoolExecutor.AbortPolicy());

        // 使用TtlExecutors包装，支持ThreadLocal传递
        return TtlExecutors.getTtlExecutorService(executor);
    }


}
class CustomThreadFactory implements ThreadFactory {
    private final AtomicInteger threadCounter = new AtomicInteger(1);
    private final String namePrefix;  // 自定义名称前缀

    public CustomThreadFactory(String namePrefix) {
        this.namePrefix = namePrefix;
    }

    @Override
    public Thread newThread(Runnable task) {
        // 格式：前缀 + 线程编号
        Thread thread = new Thread(task, namePrefix + threadCounter.getAndIncrement());
        thread.setDaemon(false);  // 非守护线程
        thread.setPriority(Thread.NORM_PRIORITY);
        return thread;
    }
}


